package cn.zxone.feishu.demo.common.handler;

import cn.zxone.feishu.demo.common.properties.FeiShuProperties;
import com.alibaba.fastjson.JSON;
import com.lark.oapi.core.enums.BaseUrlEnum;
import com.lark.oapi.core.request.EventReq;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.event.CustomEventHandler;
import com.lark.oapi.event.EventDispatcher;
import com.lark.oapi.event.cardcallback.P2CardActionTriggerHandler;
import com.lark.oapi.event.cardcallback.P2URLPreviewGetHandler;
import com.lark.oapi.event.cardcallback.model.CallBackToast;
import com.lark.oapi.event.cardcallback.model.P2CardActionTrigger;
import com.lark.oapi.event.cardcallback.model.P2CardActionTriggerResponse;
import com.lark.oapi.event.cardcallback.model.P2URLPreviewGet;
import com.lark.oapi.event.cardcallback.model.P2URLPreviewGetResponse;
import com.lark.oapi.event.cardcallback.model.URLPreviewGetInline;
import com.lark.oapi.service.contact.ContactService;
import com.lark.oapi.service.contact.v3.model.P2UserUpdatedV3;
import com.lark.oapi.ws.Client;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 *     飞书 事件回调处理
 * </p>
 * @author zhangxue
 * @since 2025-04-09 11:07:48
 */

public class EventCallbackHandler {

    /**
     * <p>
     *   构建并启动长连接客户端
     * </p>
     * @param appConfig 应用配置
     */
    public static void buildAndStart(FeiShuProperties.AppConfig appConfig) {

        String callbackMode = appConfig.getCallbackMode();

        String eventMode = appConfig.getEventMode();

        if (!("WS").equalsIgnoreCase(callbackMode) && !("WS").equalsIgnoreCase(eventMode)) {

            return;
        }

        String appId = appConfig.getAppId();

        // 构建长连接客户端
        Client client = new Client.Builder(appId, appConfig.getAppSecret())
                .autoReconnect(true)
                .domain(BaseUrlEnum.FeiShu.getUrl())
                // 构建事件回调处理
                .eventHandler(buildEventDispatcher(appConfig))
                .build();

        // 启动长连接客户端
        client.start();
    }

    /**
     * <p>
     *     构建事件回调处理
     * </p>
     * @param appConfig
     * @return {@link EventDispatcher }
     */
    private static EventDispatcher buildEventDispatcher(FeiShuProperties.AppConfig appConfig) {

        String callbackMode = appConfig.getCallbackMode();

        String eventMode = appConfig.getEventMode();

        // 长连接不需要这两个参数，请保持空字符串
        EventDispatcher.Builder builder = EventDispatcher.newBuilder(appConfig.getVerificationToken(), appConfig.getEncryptKey());

        if (("WS").equalsIgnoreCase(callbackMode)) {
            // 监听「卡片回传交互 card.action.trigger」
            builder.onP2CardActionTrigger(new P2CardActionTriggerHandler() {
                @Override
                public P2CardActionTriggerResponse handle(P2CardActionTrigger event) throws Exception {
                    System.out.printf("[ P2CardActionTrigger access ], data: %s\n", Jsons.DEFAULT.toJson(event.getEvent()));
                    P2CardActionTriggerResponse resp = new P2CardActionTriggerResponse();
                    CallBackToast toast = new CallBackToast();
                    toast.setType("info");
                    toast.setContent("卡片交互成功 from Java SDk");
                    resp.setToast(toast);
                    return resp;
                }
            });

            // 监听「拉取链接预览数据 url.preview.get」
            builder.onP2URLPreviewGet(new P2URLPreviewGetHandler() {
                @Override
                public P2URLPreviewGetResponse handle(P2URLPreviewGet event) throws Exception {
                    System.out.printf("[ P2URLPreviewGet access ], data: %s\n", Jsons.DEFAULT.toJson(event.getEvent()));
                    P2URLPreviewGetResponse resp = new P2URLPreviewGetResponse();
                    URLPreviewGetInline inline = new URLPreviewGetInline();
                    inline.setTitle("链接预览测试fromJavaSDK");
                    resp.setInline(inline);
                    return resp;
                }
            });
        }

        if (("WS").equalsIgnoreCase(eventMode)) {

            // 这里填入你要自定义订阅的 event 的 key，例如 out_approval
            builder.onP2UserUpdatedV3(new ContactService.P2UserUpdatedV3Handler() {

                @Override
                public void handle(P2UserUpdatedV3 event) throws Exception {
                    System.out.println("[ contact.user.created_v3], type: message, data: " + JSON.toJSONString(event));
                }
            });

            // 这里填入你要自定义订阅的 event 的 key，例如 out_approval
            builder.onCustomizedEvent("contact.department.created_v3", new CustomEventHandler() {
                @Override
                public void handle(EventReq event) throws Exception {
                    System.out.printf("[ contact.user.created_v3], type: message, data: %s\n", new String(event.getBody(), StandardCharsets.UTF_8));
                }
            });

        }


        return builder.build();
    }


}
